package org.example.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.example.entity.UserDTO;
import org.example.exception.CustomException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    //定义密钥(也可以放在配置springboot配置文件中或服务器环境变量中)
    //因为HS512要求超过64位
    private static final String SHARK = "abcdefghigklmnopqrstuvwxyz123456afeawefafaeasdfaefawdasdcasdfasefaabcdefghigklmnopqrstuvwxyz123456afeawefafaeasdfaefawdasdcasdfasefa";

    //过期时间expiration 两个小时
    private static final long EXPIRATION =2*60*60*1000 ;

    //生成token
    public static String generateToken(UserDTO user) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() +  EXPIRATION);
        Map<String, String> map = new HashMap<>();
        map.put("userId", String.valueOf(user.getUserId()));//存储id
        map.put("username", user.getUsername());//储存账户
//        map.put("permission", String.valueOf(user.getPermission()));
        ObjectMapper objectMapper = new ObjectMapper();
        String subject = null;
        try {
            subject = objectMapper.writeValueAsString(map);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return Jwts.builder()
                .setHeaderParam("type", "JWT")//设置头
                //存放信息载荷（Payload）中的subject字段载荷是 JWT 的核心数据部分，除了subject，还可通过其他方法添加iss（签发者）、aud（受众）等标准声明，或自定义声明。
                .setSubject(subject)
                .setIssuedAt(now)//设置 JWT 的签发时间（iat，issued at）
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, SHARK)  //采取SHA512加密算法
                .compact();//最后的组合
    }

    //解析token，获取信息
    public static Claims getClaimsVyToken(String token) {
        try{
            return Jwts.parser()
                    .setSigningKey(SHARK)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            throw new CustomException("500","token过期");
        }


    }
}
